package service

import (
	"context"
	amqp "github.com/rabbitmq/amqp091-go"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"golang-sgg-daijia/internal/const/mqconst"
)

type MqConsumer interface {

}

func NewMqConsumer(
	service *Service,
	conn *amqp.Connection,
	paymentService PaymentService,
) MqConsumer {
	mqSer := &mqConsumer{
		Service:     service,
		conn:        conn,
		paymentService: paymentService,
	}
	mqSer.StartConsumerJob(context.Background(), mqconst.RoutingPaySuccess, paymentService.HandleOrder)
	return mqSer
}

type mqConsumer struct {
	*Service
	conn *amqp.Connection
	paymentService PaymentService
}

func NewRabbitMqConsumer(conf *viper.Viper) *amqp.Connection{
	conn, err := amqp.Dial(conf.GetString("data.rabbitmq.dsn"))
	if err != nil {
		panic(err)
	}
	return conn
}

func (m *mqConsumer) StartConsumerJob(ctx context.Context, key string, JobFunc func(context.Context,[]byte)) {
	ch, err := m.conn.Channel()
	if err != nil {
		m.logger.Error("mqConsumer|StartConsumerJob|Channel", zap.Error(err))
		panic(err)
	}
	defer ch.Close()
	q, err := ch.QueueDeclare(key, true, false, false, false, nil)
	if err != nil {
		m.logger.Error("mqProducer|SendMessage|QueueDeclare", zap.Error(err))
		panic(err)
	}
	msg, err := ch.Consume(q.Name, "", true, false, false, false, nil)
	if err != nil {
		m.logger.Error("mqProducer|SendMessage|Consume", zap.Error(err))
		panic(err)
	}
	go func() {
		defer func() {
			if err := recover(); err != nil {
				m.logger.Error("mqConsumer|StartConsumerJob|Consume", zap.Error(err.(error)))
			}
		}()
		for {
			select {
			case <-ctx.Done():
				return
			case d := <-msg:
				m.logger.Info("mqConsumer|StartConsumerJob|Consume", zap.String("msg", string(d.Body)))
				JobFunc(ctx, d.Body)
			}
		}

	}()
}

